﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using AutoMapper;
using CNav.Business.Services;
using CNav.Model;
using CNav.Support;
using Microsoft.Practices.Unity;

namespace CNav.Controllers
{
    [Authorize]
    public class AccountController : BaseController
    {
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost, AllowAnonymous, ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            // Lets first check if the Model is valid or not
            if (ModelState.IsValid)
            {
                string username = model.UserName;
                string password = model.Password;
                String ipAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
                var response = Service.Get<UserAccountService>().Login(username, password, ipAddress);

                // User found in the database
                if (response.Data != null)
                {
                    var user = response.Data;
                    var userProfile = Mapper.Map<SessionUser>(user);

                    FormsAuthentication.SetAuthCookie(username, model.RememberMe);
                    Session[Constant.SessionUser] = userProfile;

                    if (userProfile.IsComplete())
                    {
                        if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                        {
                            return Redirect(returnUrl);
                        }
                        return RedirectToAction("Index", "Home");
                    }

                    if (userProfile.IsBusinessAdmin == true)
                        return RedirectToAction("Index", "UserProfile");

                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", "The email or password provided is incorrect.");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            String ipAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
            Service.Get<UserAccountService>().LogOff(LoginUser.Email, ipAddress);
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
}